package com.tudouji.project.common;

import com.flow.service.pojo.BasePojo;
import com.flow.service.pojo.ResultParam;
import com.flow.service.pojo.flow.FlowTempNode;
import com.flow.service.pojo.result.FlowResult;
import com.flow.service.process.service.IFileInfoService;
import com.flow.service.process.service.IFlowBaseService;
import com.flow.service.process.service.impl.FlowProcessProxy;
import com.flow.service.utils.FlowReloadUtil;
import com.tudouji.common.constant.Constants;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.common.utils.Sign;
import com.tudouji.common.utils.StringUtils;
import com.tudouji.common.utils.file.FileUploadUtils;
import com.tudouji.common.utils.file.FileUtils;
import com.tudouji.framework.config.RuoYiConfig;
import com.tudouji.framework.config.ServerConfig;
import com.tudouji.framework.config.TuDouJiConfig;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.project.bill.domain.Recharge;
import com.tudouji.project.bill.domain.Sellform;
import com.tudouji.project.bill.domain.Transferapply;
import com.tudouji.project.bill.mapper.RechargeMapper;
import com.tudouji.project.bill.mapper.SellformMapper;
import com.tudouji.project.bill.service.ISellformService;
import com.tudouji.project.bill.service.ITransferapplyService;
import com.tudouji.project.bill.service.IWhinfoService;
import com.tudouji.project.customer.domain.Customer;
import com.tudouji.project.customer.mapper.CustomerMapper;
import com.tudouji.project.farepay.domain.FarepayApply;
import com.tudouji.project.farepay.mapper.FarepayApplyMapper;
import com.tudouji.project.flow.utils.FlowProcessUtil;
import com.tudouji.project.harvest.domain.Freightorder;
import com.tudouji.project.harvest.domain.Procurementcontract;
import com.tudouji.project.harvest.mapper.FreightorderMapper;
import com.tudouji.project.harvest.mapper.ProcurementcontractMapper;
import com.tudouji.project.harvest.service.impl.BaseServiceFactory;
import com.tudouji.project.organization.domain.Department;
import com.tudouji.project.organization.domain.Organization;
import com.tudouji.project.organization.mapper.DepartmentMapper;
import com.tudouji.project.organization.mapper.OrganizationMapper;
import com.tudouji.project.organization.service.IOrganizationService;
import com.tudouji.project.organization.service.ISupplierService;
import com.tudouji.project.pay.domain.Payinfo;
import com.tudouji.project.pay.mapper.PayinfoMapper;
import com.tudouji.project.permission.service.ISalespermissionService;
import com.tudouji.project.produce.domain.Materialretapply;
import com.tudouji.project.produce.domain.Pickinglist;
import com.tudouji.project.produce.domain.Whinapply;
import com.tudouji.project.produce.mapper.MaterialretapplyMapper;
import com.tudouji.project.produce.mapper.PickinglistMapper;
import com.tudouji.project.produce.service.IWhinapplyService;
import com.tudouji.project.product.service.IProductinfoService;
import com.tudouji.project.product.service.ISalesspecificationService;
import com.tudouji.project.purchasebill.domain.Purchasebill;
import com.tudouji.project.purchasebill.service.IPurchasebillService;
import com.tudouji.project.store.domain.Storeroom;
import com.tudouji.project.store.mapper.StoreroomMapper;
import com.tudouji.project.store.service.IStockunitService;
import com.tudouji.project.store.service.IStorehouseroomService;
import com.tudouji.project.store.service.IStoreroomService;
import com.tudouji.project.system.domain.Label;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.service.ILabelService;
import com.tudouji.project.system.service.ISysUserService;
import com.tudouji.project.system.service.IUpimageService;
import com.tudouji.project.system.service.impl.FileinfoServiceImpl;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.weixin4j.WeixinException;
import org.weixin4j.model.js.Ticket;
import org.weixin4j.spring.WeixinTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 通用请求处理
 *
 * @author ruoyi
 */
@RestController
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private IUpimageService upimageService;

    @Autowired
    private ISalespermissionService salespermissionService;
    @Autowired
    private IStockunitService stockunitService;
    @Autowired
    private IOrganizationService organizationService;
    @Autowired
    private IStoreroomService storeroomService;
    @Autowired
    private IStorehouseroomService storehouseroomService;
    @Autowired
    private IProductinfoService productinfoService;
    @Autowired
    private ISalesspecificationService salesspecificationService;
    @Autowired
    private ISupplierService supplierService;
    @Autowired
    private FlowProcessUtil flowProcessUtil;
    @Autowired
    private FlowProcessProxy processProxy;
    @Autowired
    private ILabelService labelService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IPurchasebillService purchasebillService;
    @Autowired
    private StoreroomMapper storeroomMapper;

    @Autowired
    @Qualifier("fileInfoService")
    private IFileInfoService fileInfoService;
    @Autowired
    private FileinfoServiceImpl fileinfoService;
    @Autowired
    private CommonServiceImpl commonService;

    @Autowired
    private ITransferapplyService transferapplyService;
    @Autowired
    private ISellformService sellformService;

    @Autowired
    private IWhinfoService whinfoService;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private PickinglistMapper pickinglistMapper;

    @Autowired
    private IWhinapplyService whinapplyService;

    @Autowired
    private MaterialretapplyMapper materialretapplyMapper;
    @Autowired
    private SellformMapper sellformMapper;
    @Autowired
    private RechargeMapper rechargeMapper;
    @Autowired
    private FarepayApplyMapper farepayApplyMapper;
    @Autowired
    private DepartmentMapper departmentMapper;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private ProcurementcontractMapper procurementcontractMapper;
    @Autowired
    private FreightorderMapper freightorderMapper;
    @Autowired
    private PayinfoMapper payinfoMapper;
    @Autowired
    private WeixinTemplate weixinTemplate;
    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = TuDouJiConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file, Integer fileType, String busTable) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            long id = fileInfoService.insertTableFile(file, filePath, fileName, fileType, busTable);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("id", id);
            ajax.put("originalName", file.getOriginalFilename());
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            ajax.put("defineId", fileType);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求(旧)
     */
    @PostMapping("/common/uploadImage")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = TuDouJiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String id = upimageService.insertUpimage(file, filePath, fileName);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("id", id);
            ajax.put("originalName", file.getOriginalFilename());
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = TuDouJiConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通过权限code，就是permissondef中的code,对应salepermission中的permission获取部门列表
     *
     * @return
     */
    @GetMapping("/getDepsByPermissionCode")
    public AjaxResult getDepsByPermissionCode(Integer code, @RequestParam(required = false) String deptStats) {

        return AjaxResult.success(salespermissionService.getDepsByPermissionCode(code, deptStats));
    }

    /**
     * 获取组织列表
     *
     * @return
     */
    @GetMapping("/getOrgs")
    public AjaxResult getOrgs(@RequestParam(required = false) Integer type) {
        return AjaxResult.success(organizationService.getOrgs(type));
    }

    /**
     * 通过组织＆权限获取库房列表
     * permissionFlag:默认不传值:查询所有库房；1:通过用户所有权限查询2：通过用户指定权限查询
     * permissionId:如果permissionFlag设置为2：则必须传递此参数，此参数对应想要查询的指定权限ID
     *
     * @return getPermisForStore
     */
    @ApiOperation(value = "通过组织＆权限获取库房列表", notes = "通过组织＆权限获取库房列表", httpMethod = "GET")
    @GetMapping("/getStoreRoomByOrgIdOrPermissions")
    public AjaxResult getStoreRoomByOrgIdOrPermissions(@RequestParam(required = false) String guid
            , @RequestParam(required = false) Integer enable
            , @RequestParam(required = false) Integer type
            , @RequestParam(required = false) Integer send
            , @RequestParam(required = false) Integer flag
            , @RequestParam(required = false) Integer permissionFlag
            , @RequestParam(required = false) Integer permissionId
            , @RequestParam(required = false) String functionType) {

        return AjaxResult.success(storeroomService.getStoreRoomByOrgIdOrPermissions(guid, enable, type, send, flag, permissionFlag, functionType, permissionId));
    }

    @ApiOperation(value = "通过组织部门内外部条件获取库房列表", notes = "通过组织部门内外部条件获取库房列表", httpMethod = "GET")
    @GetMapping("/getStoreRoomsByCondition")
    public AjaxResult getStoreRoomsByCondition(@NotNull @RequestParam String orgguid , @NotNull @RequestParam Long deptId
            , @NotNull @RequestParam Integer innerOut) {

        return AjaxResult.success(storeroomService.getStoreRoomsByCondition(orgguid, deptId, innerOut));
    }

    /**
     * FlowProcessServiceImpl
     * 通过库房获取库间
     *
     * @param id    库房id
     * @param type  库间类型
     * @param stats 状态（1-启用，2-未启用）
     * @return getPermisForStore
     */
    @GetMapping("/getStoreHouseRoomByRoomId")
    public AjaxResult getStoreHouseRoomByRoomId(Long id, Integer type, @RequestParam(required = false) String stats) {
        return AjaxResult.success(storehouseroomService.getStoreHouseRoomByRoomId(id, type, stats));
    }

    /**
     * 根据产品类型获取产品
     *
     * @param productflag 产品类型
     * @param category    品类id
     * @return
     */
    @GetMapping("/getProducts")
    public AjaxResult getProducts(@RequestParam(required = false) String productflag
            , @RequestParam(required = false) String category) {
        return AjaxResult.success(productinfoService.getProducts(productflag, category));
    }

    /**
     * 根据产品获取物料（规格）列表
     *
     * @param productGuid 产品id
     * @param valuation   计价方式:1-按件,2-按吨
     * @param stats       状态:1-启用 2-禁用
     * @param brandid     品牌id
     * @param flag        产品标识:1-单品，2-套装
     * @return
     */
    @GetMapping("/getSpecs")
    public AjaxResult getSpecs(@RequestParam(required = false) String productGuid
            , @RequestParam(required = false) Integer valuation
            , @RequestParam(required = false) String stats
            , @RequestParam(required = false) String brandid
            , @RequestParam(required = false) Integer flag
            , @RequestParam(required = false) String name
            , @RequestParam(required = false) Integer type) {
        return AjaxResult.success(salesspecificationService.getSpecs(productGuid, valuation, stats, brandid, flag, name, type));
    }

    /**
     * 获取供应商列表
     *
     * @param types 供应商类型集合
     * @return
     */
    @GetMapping("/getSuppliers")
    public AjaxResult getSuppliers(@RequestParam(required = false) String types) {
        return AjaxResult.success(supplierService.getSuppliers(types));
    }

    /**
     * 获取审批流程
     *
     * @return
     */
    @GetMapping("/getNodes")
    public AjaxResult getNodes(Long orderid, Long flowid) {
//		List<Object> list = processService.getFlownodes(orderid, flowid, orgId, deptId,platformId);
        BasePojo base = null;

        IFlowBaseService baseService=BaseServiceFactory.getFlowBaseServiceById(flowid);
        log.info("====Here we get baseService :" + baseService);
        if (baseService!=null){
            base=baseService.getBaseById(orderid);
            base.prepareForProcess();
            List<Object> list = flowProcessUtil.getApprovalRecord(orderid, flowid, base);
            return AjaxResult.success(list);
        }

        if (flowid.equals(new Long(26))) {
            Purchasebill purchasebill = purchasebillService.selectPurchasebillById(orderid);
            base = purchasebill;
            Storeroom storeroom = storeroomMapper.selectStoreroomByGuid(purchasebill.getSrguid());
            base.setPlatformId(Long.valueOf(storeroom.getId()));
        }else if(flowid.equals(new Long(27))||flowid.equals(new Long(28))){
            Transferapply apply=transferapplyService.selectTransferapplyByNewId(orderid);
            base = apply;
            base.setPlatformId(apply.getFromsrId());
            base.setToPlatformId(apply.getTosrId());
        }else if (flowid.equals(new Long(29))) {
            Customer customer = customerMapper.selectCustomerByNewId(orderid);
            base = customer;
        }else if (flowid.equals(new Long(30))) {
            Pickinglist pickinglist = pickinglistMapper.selectPickinglistByNewId(orderid);
            base = pickinglist;
        }else if (flowid.equals(new Long(33))) {
            Whinapply apply = whinapplyService.selectWhinapplyByAutoId(orderid);
            base = apply;
            base.setPlatformId(apply.getStrmId());
        }else if (flowid.equals(new Long(31))) {
            Materialretapply apply = materialretapplyMapper.selectMaterialretapplyByNewId(orderid);
            base = apply;
            base.setPlatformId(apply.getStrmId());
        }else if (flowid.equals(new Long(34)) ||
                flowid.equals(new Long(35)) || flowid.equals(new Long(36))
                ||flowid.equals(new Long(2))   ) {
            Sellform apply = sellformMapper.selectSellformById(orderid);
            base = apply;
            base.setPlatformId(apply.getStrmId());
        }else if(flowid.equals(new Long(37))){
            Recharge apply = rechargeMapper.selectRechargeByNewId(orderid);
//            base.setPlatformId(apply.getStrmId());
            Department department = departmentMapper.selectDepartmentById(apply.getDepartid());
            apply.setDeptId(department.getId());
            base = apply;
        }else if(flowid.equals(new Long(38))){
            FarepayApply apply = farepayApplyMapper.selectFarepayApplyById(String.valueOf(orderid));
//            base.setPlatformId(apply.getStrmId());
            Department department = departmentMapper.selectDepartmentById(apply.getDepartid());
            apply.setDeptId(department.getId());
            Organization organization = organizationMapper.selectOrganizationById(apply.getOrgguid());
            apply.setOrgId(organization.getId());
            base = apply;
        }else if(flowid.equals(new Long(39))){
            Procurementcontract apply = procurementcontractMapper.selectProcurementcontractByNewId(orderid);
            base = apply;
        }else if(flowid.equals(new Long(40))){
            Freightorder apply = freightorderMapper.selectFreightorderByAutoId(orderid);
            base = apply;
            Storeroom storeroom = storeroomMapper.selectStoreroomByGuid(apply.getStrguid());
            base.setPlatformId(Long.valueOf(storeroom.getId()));
        }else if(flowid.equals(new Long(41))){
            Payinfo apply = payinfoMapper.selectPayinfoByAutoId(orderid);
            base = apply;
            base.setPlatformId(apply.getStorermId());
        }else if(flowid.equals(new Long(42))){
            Payinfo apply = payinfoMapper.selectPayinfoByAutoId(orderid);
            base = apply;
            base.setPlatformId(apply.getStorermId());
        }

        log.info("-------base----orgId:{}",base.getOrgId());
        log.info("----deptId：{}",base.getDeptId());
        log.info("----PlatformId：{}",base.getPlatformId());

        List<Object> list = flowProcessUtil.getApprovalRecord(orderid, flowid, base);
        return AjaxResult.success(list);
    }


    @GetMapping("/getTabsByFlowId")
    public AjaxResult getTabsByFlowId(Long flowId) {
        List<Label> list = labelService.selectLabelListByFlowId(flowId);
        return AjaxResult.success(list);
    }


    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo(HttpServletRequest request) {
        return userService.userService(request);

    }

    /**
     * 获取可拒绝节点
     *
     * @param orderid
     * @param taskid
     * @return
     */
    @GetMapping("/getRefuseNodes")
    public AjaxResult getRefuseNodes(Long orderid, Long taskid) {
        log.info("----------orderid------" + orderid + "----" + taskid);
        List<com.flow.service.pojo.flow.FlowTempNode> list = flowProcessUtil.getRefuseNodes(orderid, taskid);
        return AjaxResult.success(list);
    }

    /**
     * 转交
     *
     * @param taskId   当前taskId
     * @param toUserId 转交对象id
     * @return
     */
    @PostMapping("/transmit")
    public AjaxResult transmit(Long taskId, Long toUserId, String opinion, String fileIds) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        FlowResult result = processProxy.transmit(taskId, user, toUserId, opinion, fileIds);
        if (result.getMsg().equals(ResultParam.SUCCESS)) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error(result.getMsg());
        }
    }

    /**
     * 特殊节点处理模块-获取业务单及对应特殊节点
     *
     * @param flowTempId 流程id
     * @param code       业务单据编号
     * @return 拒绝
     */
    @GetMapping("/getRejectNodeByCode")
    public AjaxResult transmit(Long flowTempId, String code) {
        BasePojo basePojo = null;
        if (26 == flowTempId) {
            Purchasebill apply = purchasebillService.selectPurchasebillByCode(code);
            List<FlowTempNode> nodes = processProxy.getSpecifedNode(flowTempId, apply.getStatus());
//            List<FlowTempNode> nodes = apply.getNodes();
//            selectRejectNodeByAnnex(nodes);
            apply.setNodes(nodes);
            basePojo = apply;
        }
        if (28 == flowTempId) {
            Transferapply apply = transferapplyService.selectTransferapplyByCode(code);
            List<FlowTempNode> nodes = processProxy.getSpecifedNode(flowTempId, apply.getStatus());
//            List<FlowTempNode> nodes = apply.getNodes();
//            selectRejectNodeByAnnex(nodes);
            apply.setNodes(nodes);
            basePojo = apply;
        }
        if (34 == flowTempId || 35 == flowTempId || 36 == flowTempId) {
            Sellform sellform = new Sellform();
            sellform.setFlowtempguid(flowTempId+"");
            sellform.setSellcode(code);
            sellform = sellformService.selectSellformRejectByCode(sellform);

            List<FlowTempNode> nodes = processProxy.getSpecifedNode(flowTempId, sellform.getStatus());
//            List<FlowTempNode> nodes = apply.getNodes();
//            selectRejectNodeByAnnex(nodes);
            basePojo = sellform;
            sellform.setNodes(nodes);
            if (sellform != null){
                basePojo.setCode(sellform.getSellcode());
                basePojo.setCreateName(sellform.getApplyname());
            }
        }
        if (40 == flowTempId) {
            Freightorder apply = freightorderMapper.selectFreightorderByCode(code);
            List<FlowTempNode> nodes = processProxy.getSpecifedNode(flowTempId, apply.getStatus());
//            List<FlowTempNode> nodes = apply.getNodes();
//            selectRejectNodeByAnnex(nodes);
            apply.setNodes(nodes);
            basePojo = apply;
        }
        if (41 == flowTempId) {
            Payinfo apply = payinfoMapper.selectPayinfoByCode(code);
            List<FlowTempNode> nodes = processProxy.getSpecifedNode(flowTempId, apply.getStatus());
//            List<FlowTempNode> nodes = apply.getNodes();
//            selectRejectNodeByAnnex(nodes);
            apply.setNodes(nodes);
            basePojo = apply;
        }
        if (42 == flowTempId) {
            Payinfo apply = payinfoMapper.selectPayinfoByCode(code);
            List<FlowTempNode> nodes = processProxy.getSpecifedNode(flowTempId, apply.getStatus());
//            List<FlowTempNode> nodes = apply.getNodes();
//            selectRejectNodeByAnnex(nodes);
            apply.setNodes(nodes);
            basePojo = apply;
        }
        return AjaxResult.success(basePojo);
    }

    private void selectRejectNodeByAnnex(List<FlowTempNode> nodes) {
        if (nodes.size() > 0){
            for (int i = 0; i < nodes.size(); i++) {
                FlowTempNode node = nodes.get(i);
                String annex = node.getAnnex();
                String annexA = annex.replace("status", "");
                if(annexA.contains(">=")){
                    if (!(node.getFlowStat() >= Integer.parseInt(annexA.replace(">=", "")))){
                        nodes.remove(node);
                        continue;
                    }
                }
                if(annexA.contains(">") && !annexA.contains("=")){
                    if (!(node.getFlowStat() > Integer.parseInt(annexA.replace(">", "")))){
                        nodes.remove(node);
                        continue;
                    }
                }
                if(annexA.contains("==")){
                    if (!(node.getFlowStat() == Integer.parseInt(annexA.replace("==", "")))){
                        nodes.remove(node);
                        continue;
                    }
                }
                if(annexA.contains("<") && !annexA.contains("=")){
                    if (!(node.getFlowStat() < Integer.parseInt(annexA.replace("<", "")))){
                        nodes.remove(node);
                        continue;
                    }
                }
                if(annexA.contains("<=")){
                    if (!(node.getFlowStat() <= Integer.parseInt(annexA.replace("<=", "")))){
                        nodes.remove(node);
                        continue;
                    }
                }
            }
        }
    }

    @PostMapping("/backApproval")
    public AjaxResult backApproval(Long id, Long nodeId, Long flowId, String content, String fileIds) {
        return commonService.backApproval(id, nodeId, flowId, content, fileIds);
    }

    /**
     * 获取用户permission
     *
     * @return
     */
    @GetMapping("/getPermis")
    public AjaxResult getPermis(@RequestParam(required = false) Integer id) {
        return salespermissionService.getPermis(id);
    }

    /**
     * 通过规格ID获取单位
     *
     * @return
     */
    @ApiOperation(value = "通过规格ID获取单位", notes = "通过规格ID获取单位", httpMethod = "GET")
    @GetMapping("/getUnits")
    public AjaxResult getUnits(@RequestParam String speguid) {
        return stockunitService.getUnits(speguid);
    }

    @GetMapping("/getPLInfo")
    public AjaxResult getPLInfo(@RequestParam(required = false) Long strmid, @RequestParam(required = false) String shrtype
            , @RequestParam(required = false) String productid, @RequestParam(required = false) String spec
            , @RequestParam(required = false) String orgid) {
        return whinfoService.getPLInfo(strmid, shrtype,productid,spec,orgid);
    }

    /**
     * 刷新流程服务内存缓存
     *
     * @return
     */
    @ApiOperation(value = "刷新流程服务内存缓存", notes = "刷新流程服务内存缓存", httpMethod = "GET")
    @GetMapping("/allNeedReload")
    public AjaxResult allNeedReload() {
        FlowReloadUtil.allNeedReload();
        return AjaxResult.success();
    }

    /**
     * 通用删除请求
     */
    @PostMapping("/common/delete")
    public AjaxResult deleteFile(Long id){
        try {
            fileinfoService.deleteFileinfoById(id);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    @GetMapping(value = "/getWXconfig", produces = "application/json; charset=utf-8")
    @ApiImplicitParam(paramType = "query", dataType = "string", name = "url",required = true ,value = "当前网页的URL，不包含#及其后面部分")
    public AjaxResult getConfig(@RequestParam("url") String url) {
        try {
            String appId = weixinTemplate.getAppId();
            Ticket ticket = weixinTemplate.getJsApiTicket();
            Map<String, String> params = Sign.sign(ticket.getTicket(), url);
            params.put("appId", appId);
            return  AjaxResult.success(params);
        } catch (WeixinException e) {
            throw new RuntimeException(e);
        }

    }
}
